import axios from 'axios'
import qs from 'qs'
import {ElMessage, ElLoading} from 'element-plus'
import cache from '@/utils/cache'

 
// const api_base_url = 'http://win.xisofttec.com:37735/design';
const api_base_url = 'http://localhost:50001';
// axios实例
const service = axios.create({
    // baseURL: import.meta.env.VITE_API_URL as any,
    baseURL: api_base_url,
    
    timeout: 60000,
    headers: {'Content-Type': 'application/json;charset=UTF-8'}
})                               

// 请求拦截器
service.interceptors.request.use(
    (config: any) => {
        config.headers['Accept-Language'] = cache.getLanguage()

        // 追加时间戳，防止GET请求缓存
        if (config.method?.toUpperCase() === 'GET') {
            config.params = {...config.params, t: new Date().getTime()}
        }

        if (Object.values(config.headers).includes('application/x-www-form-urlencoded')) {
            config.data = qs.stringify(config.data)
        }

        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        if (response.status !== 200) {
            return Promise.reject(new Error(response.statusText || 'Error'))
        }

        const res = response.data
        loading.close()
        // 响应成功
        if (res.code === 0 || res.code == "0" || res.code === 200 || res.code == "200") {
            return res
        }

        // 错误提示
        ElMessage.error(res.msg)

        return Promise.reject(new Error(res.msg || 'Error'))
    },
    error => {
        ElMessage.error(error.message)
        return Promise.reject(error)
    }
)

// 导出 axios 实例
export default service
